#!/bin/bash

IMG_DIR=/var/lib/libvirt/images           //定义变量，虚拟机文件存放的位置
BASE_VM=rhel6test                    //定义变量，基础虚拟机的名字
E_NOINPUT=65                          //定义输出错误编码
E_NOTNUM=66
E_OUT_OF_RANGE=67
E_VM_EXISTS=68

read -p "please input a vm  number(0-254): " NEW_VMNU                //交互式输入增量虚拟机的编号
if [ -z $NEW_VMNU ]; then                                  //判断编号是否为空
  echo "You must input a number."
  exit $E_NOINPUT
fi

if [ $NEW_VMNU != $(echo  "$NEW_VMNU*1" | bc) ]; then         //判断编号是否为字符
  echo "You must input a number."
  exit $E_NOTNUM
fi

if [ $NEW_VMNU -lt 1 -o $NEW_VMNU -gt  254 ]; then          //判断编号是否超出了1-254范围
  echo "You must input a number between 1 and 254"
  exit $E_OUT_OF_RANGE
fi

NEW_VM=${BASE_VM}node${NEW_VMNU}                    //定义增量虚拟机的名字

if [ -e $IMG_DIR/$NEW_VM.img ]; then                 //判断增量虚拟机编号是否重复
  echo "$NEW_VM already exists"
  exit $E_VM_EXISTS
fi

echo -en "creating disk  image......\t\t"         //-en选项，不换行输出，为了连接下面的ok
qemu-img create -b  $IMG_DIR/$BASE_VM.img -f qcow2 $IMG_DIR/$NEW_VM.img &> /dev/null
echo -e "\e[32m[OK]\e[0m"                         //高亮显示输出内容：[ok]
echo                                              //echo后面不接选项和参数，输出空行

virsh dumpxml $BASE_VM  > /tmp/$BASE_VM.xml            //生成克隆虚拟机XML文件

MAC_ADDR=$(echo  "obase=16;$NEW_VMNU" | bc)            //定义mac地址后两位数字

sed -i  "/<name>$BASE_VM/s/$BASE_VM/$NEW_VM/" /tmp/$BASE_VM.xml          //XML文件需要修改的四处
sed -i  "/<uuid>/s/<uuid>.\{36\}/<uuid>$(uuidgen)/"  /tmp/$BASE_VM.xml
sed -i  "/$BASE_VM\.img/s/$BASE_VM\.img/$NEW_VM\.img/" /tmp/$BASE_VM.xml
sed -i "/mac  address/s/00'/$MAC_ADDR'/" /tmp/$BASE_VM.xml

virsh define  /tmp/$BASE_VM.xml &> /dev/null               //定义新的虚拟机

echo "$NEW_VM created successful  !!!"

